﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using hospital_registration_system.Entity;
using hospital_registration_system.Utility;
using hospital_registration_system.DAL;
namespace hospital_registration_system.user
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Departments> departments = UserPatients.searchAllDepartments();//查询所有科室
            Patients patient = (Patients)Session["patient"];
            Session.Add("departments", departments);
            nick.Text = patient.Nickname;
            name.Text = patient.Patient_name;
            tel.Text = patient.Telephone;
            age.Text = patient.Age+"";
            sex.Text = patient.Sex;
            id.Text = patient.Id + "";
            state.Text = patient.State + "";
            if (!IsPostBack)
            {
                gdvAppointmentBind();
                ddlDateDepBind();//科室下拉列表数据绑定
                ddlIllBind();//疾病下拉列表数据绑定
            }
        }

//通过科室预约挂号------------------------------------------------------------------------------------------

        //通过科室预约选择的日期存放到label里
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //将选择的日期存放到label里
            lblState.Text = calDate.SelectedDate.ToShortDateString();
            ddlDateDep_SelectedIndexChanged(sender, e);//绑定数据
        }

        /// <summary>
        /// 绑定按科室查询可挂号时段的下拉列表，即查询所有科室
        /// </summary>
        protected void ddlDateDepBind()
        {
            List<Departments> departments = (List<Departments>)Session["departments"];
            ddlDateDep.Items.Clear();
            foreach (Departments d in departments)
            {
                ddlDateDep.Items.Add(new ListItem(d.Department_name));//没有重复的科室名
            }
        }

        //创建全局变量，用于后续查询医生信息
        private static List<Clinic_time> tx = null;

        /// <summary>
        /// 绑定挂号按科室查询出的挂号表信息
        /// </summary>
        protected void gdvClinic_timeBind(DateTime time, int id)
        {
            tx = UserClinic_Time.findClinic_TimeByDepartmentsIdAndTime(time, id);
            List<BoxedClinic_time> times = new List<BoxedClinic_time>();
            DoctorDao dao = new DoctorDao();
            foreach (Clinic_time c in tx)
            {
                //重新封装
                BoxedClinic_time boxed = new BoxedClinic_time();
                boxed.Id = c.Id;
                boxed.Doctor_name = dao.selectById(c.Doctor_id).Doctor_name;
                if (c.See_time == 1)
                {
                    boxed.See_time = "9:00~12:00";
                }
                else
                {
                    boxed.See_time = "14:00~17:00";
                }
                boxed.Treatment = c.Treatment.Year + "/" + c.Treatment.Month + "/" + c.Treatment.Year;
                boxed.Count = 100 - c.State;
                if (boxed.Count < 0) boxed.Count = 0;
                times.Add(boxed);
            }
            if (tx.Count == 0)
            {
                BoxedClinic_time boxed = new BoxedClinic_time();
                boxed.Id = -1;
                boxed.Doctor_name = "无数据";
                boxed.See_time = "无数据";
                boxed.Treatment = "无数据";
                times.Add(boxed);
            }

            gdvClinic_time.DataSource = times;
            gdvClinic_time.DataBind();
        }


        /// <summary>
        /// 在选项变化时修改查询到的可挂号时段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlDateDep_SelectedIndexChanged(object sender, EventArgs e)
        {

            int id = -1;
            List<Departments> departments = (List<Departments>)Session["departments"];
            foreach (Departments d in departments)
            {
                if (d.Department_name.Equals(ddlDateDep.Text))//由于科室名唯一，所以只用查询科室名对应的id即可
                {
                    id = d.Id;
                }
            }
            if (id == -1)
            {
                return;
            }
            DateTime time;
            //若出现转换异常，则说明程序执行错误
            try
            {
                time = DateTime.Parse(lblState.Text);
            }
            catch (FormatException ex)
            {
                string msg = ex.Message;
                return;
            }
            //绑定数据
            gdvClinic_timeBind(time, id);
        }

        /// <summary>
        /// 提交通过科室预约的挂号信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            DoctorDao dao = new DoctorDao();
            Clinic_timeDao dao2 = new Clinic_timeDao();

            AppointmentDao dao1 = new AppointmentDao();
            Dictionary<string, object> check = new Dictionary<string, object>();

            List<Departments> departments = (List<Departments>)Session["departments"];//从session中取出查到的科室信息
            int clinic_timeId = int.Parse(gdvClinic_time.SelectedValue.ToString());
            check.Add("clinic_time_id", clinic_timeId);
            int patient_id = ((Patients)Session["patient"]).Id;//获取当前登录的病人的id
            check.Add("patient_id", patient_id);
            //检查是否重复预约
            List<Appointment> appointment = dao1.selectByMap(check);
            if (appointment.Count != 0)
            {
                Response.Write("<script language=javascript>alert('当前时段您已预约过');</script>");
                return;
            }
            Clinic_time time = dao2.selectById(clinic_timeId);
            //限制挂号数
            if (time.State < 100)
            {
                int depId = -1;
                foreach (Departments d in departments)
                {
                    if (ddlDateDep.SelectedValue.ToString().Equals(d.Department_name))
                    {
                        depId = d.Id;
                    }
                }
                //从疾病与科室关系表中找到对应的疾病id,由于一个科室对应一个疾病，一个疾病对应多个科室，所以由科室查询疾病时最多返回一条结果
                int illness_id = -1;
                int doctor_id = -1;
                int department_id = -1;

                string CREATED_BY = ((Patients)Session["patient"]).Patient_name;
                foreach (Clinic_time c in tx)
                {
                    if (c.Id == clinic_timeId)
                    {
                        doctor_id = c.Doctor_id;
                        department_id = dao.selectById(doctor_id).Department_id;
                        break;
                    }
                }

                if (doctor_id != -1 && department_id != -1 && patient_id != -1)
                {
                    dao1.insert(patient_id, illness_id, department_id, doctor_id, clinic_timeId);
                    Response.Write("<script language=javascript>alert('预约成功');</script>");//弹出提示
                    gdvClinic_time.EditIndex = -1;
                }
                else
                {
                    Response.Write("<script language=javascript>alert('插入失败');</script>");//弹出提示
                }

                dao2.countAdd(clinic_timeId);//本时段预约数+1
                gdvAppointmentBind();//重新绑定挂号信息
                ddlDateDep_SelectedIndexChanged(sender, e);//重新绑定
            }
            else
            {
                Response.Write("<script language=javascript>alert('超过挂号人数');</script>");//弹出提示
            }
        }

//通过疾病和科室预约挂号-------------------------------------------------------------------------------------

        //通过疾病预约选择的日期存放到label里
        protected void btnSubmit_Click1(object sender, EventArgs e)
        {
            //将选择的日期存放到label里
            lblState1.Text = calDate1.SelectedDate.ToShortDateString();
            ddlIll_SelectedIndexChanged(sender, e);//绑定数据
        }

        private static List<Illness> illness = null;
        /// <summary>
        /// 绑定按疾病查询可挂号时段的下拉列表，即查询所有疾病
        /// </summary>
        protected void ddlIllBind()
        {
            IllnessDao dao = new IllnessDao();
            illness = dao.selectAll();
            ddlIll.Items.Clear();
            foreach (Illness il in illness)
            {
                ddlIll.Items.Add(new ListItem(il.Illness_name));
            }
            ddlDateDep1bind(illness[0].Id);//没有重复的疾病名
        }

        /// <summary>
        /// 根据疾病id查询出的科室链表
        /// </summary>
        private static List<Departments> departmentsWithIlls = null;
        /// <summary>
        /// 绑定根据疾病查找科室的功能下拉列表
        /// </summary>
        /// <param name="illsId"></param>
        protected void ddlDateDep1bind(int illsId)
        {
            departmentsWithIlls = UserPatients.searchDepartmentsByPatientId(illsId);
            ddlDateDep1.Items.Clear();
            foreach (Departments d in departmentsWithIlls)
            {
                ddlDateDep1.Items.Add(new ListItem(d.Department_name));
            }
        }

        /// <summary>
        /// 在疾病选项变化时修改查询到的可选科室
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlIll_SelectedIndexChanged(object sender, EventArgs e)
        {
            string illName = ddlIll.SelectedValue.ToString();
            int illId = -1;
            foreach (Illness ill in illness)
            {
                if (ill.Illness_name.Equals(illName))
                {
                    illId = ill.Id;
                }
            }
            if (illId == -1)
            {
                Response.Write("<script language=javascript>alert('未找到该疾病的id');</script>");//弹出提示
                return;
            }
            ddlDateDep1bind(illId);
            ddlDateDep1_SelectedIndexChanged(sender, e);
        }

        /// <summary>
        /// 提交通过疾病预约的挂号信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button3_Click(object sender, EventArgs e)
        {
            DoctorDao dao = new DoctorDao();
            Clinic_timeDao dao2 = new Clinic_timeDao();
            AppointmentDao dao1 = new AppointmentDao();
            Illness_departmentsDao illness_DepartmentsDao = new Illness_departmentsDao();


            Dictionary<string, object> check = new Dictionary<string, object>();

            
            int clinic_timeId = int.Parse(gdvClinic_time1.SelectedValue.ToString());
            string illName = ddlIll.SelectedValue.ToString();
            check.Add("clinic_time_id", clinic_timeId);
            int patient_id = ((Patients)Session["patient"]).Id;//获取当前登录的病人的id
            check.Add("patient_id", patient_id);
            //检查是否重复预约
            List<Appointment> appointment = dao1.selectByMap(check);
            if (appointment.Count != 0)
            {
                Response.Write("<script language=javascript>alert('当前时段您已预约过');</script>");
                return;
            }
            Clinic_time time = dao2.selectById(clinic_timeId);
            //限制挂号数
            if (time.State < 100)
            {
                int depId = -1;
                int illness_id = -1;
                foreach (Departments d in departmentsWithIlls)
                {
                    //查找预约的科室信息
                    if (ddlDateDep1.SelectedValue.ToString().Equals(d.Department_name))
                    {
                        depId = d.Id;
                    }
                }
                foreach(Illness ill in illness)
                {
                    //查找预约的疾病信息
                    if (ill.Illness_name.Equals(illName))
                    {
                        illness_id = ill.Id;
                        break;
                    }
                }

                int doctor_id = time.Doctor_id;
                int department_id = depId;

                if (illness_id != -1 && doctor_id != -1 && department_id != -1 && patient_id != -1)
                {
                    dao1.insert(patient_id, illness_id, department_id, doctor_id, clinic_timeId);
                    Response.Write("<script language=javascript>alert('预约成功');</script>");//弹出提示
                    gdvClinic_time.EditIndex = -1;
                }
                else
                {
                    Response.Write("<script language=javascript>alert('插入失败');</script>");//弹出提示
                }

                dao2.countAdd(clinic_timeId);//本时段预约数+1
                gdvAppointmentBind();//重新绑定挂号信息
                ddlDateDep1_SelectedIndexChanged(sender, e);//重新绑定
            }
            else
            {
                Response.Write("<script language=javascript>alert('超过挂号人数');</script>");//弹出提示
            }
        }


        /// <summary>
        /// 绑定挂号按科室查询出的挂号表信息
        /// </summary>
        protected void gdvClinic_time1Bind(DateTime time, int id)
        {
            tx = UserClinic_Time.findClinic_TimeByDepartmentsIdAndTime(time, id);
            List<BoxedClinic_time> times = new List<BoxedClinic_time>();
            DoctorDao dao = new DoctorDao();
            foreach (Clinic_time c in tx)
            {
                //重新封装
                BoxedClinic_time boxed = new BoxedClinic_time();
                boxed.Id = c.Id;
                boxed.Doctor_name = dao.selectById(c.Doctor_id).Doctor_name;
                if (c.See_time == 1)
                {
                    boxed.See_time = "9:00~12:00";
                }
                else
                {
                    boxed.See_time = "14:00~17:00";
                }
                boxed.Treatment = c.Treatment.Year + "/" + c.Treatment.Month + "/" + c.Treatment.Year;
                boxed.Count = 100 - c.State;
                if (boxed.Count < 0) boxed.Count = 0;
                times.Add(boxed);
            }
            if (tx.Count == 0)
            {
                BoxedClinic_time boxed = new BoxedClinic_time();
                boxed.Id = -1;
                boxed.Doctor_name = "无数据";
                boxed.See_time = "无数据";
                boxed.Treatment = "无数据";
                times.Add(boxed);
            }
            gdvClinic_time1.DataSource = times;
            gdvClinic_time1.DataBind();
        }

        //在通过疾病查询时，科室下拉列表修改触发
        protected void ddlDateDep1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = -1;
            foreach (Departments d in departmentsWithIlls)
            {
                if (d.Department_name.Equals(ddlDateDep1.Text))//由于科室名唯一，所以只用查询科室名对应的id即可
                {
                    id = d.Id;
                }
            }
            if (id == -1)
            {
                return;
            }
            DateTime time;
            //若出现转换异常，则说明程序执行错误
            try
            {
                time = DateTime.Parse(lblState1.Text);
            }
            catch (FormatException ex)
            {
                string msg = ex.Message;
                return;
            }
            //绑定数据
            gdvClinic_time1Bind(time, id);
        }




//显示挂号记录----------------------------------------------------------------------------------------------

        /// <summary>
        /// 绑定挂号记录数据源
        /// </summary>
        protected void gdvAppointmentBind()
        {
            Patients patient = (Patients)Session["patient"];
            gdvAppointment.DataSource = UserPatients.findMyMedicalRedcordByPatientsId(patient.Id);
            gdvAppointment.DataBind();
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gdvAppointment_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string msg = "";
            string departID = gdvAppointment.DataKeys[e.RowIndex].Values["id"].ToString(); //取出要删除记录的主键值
            if (departID.Equals("-1")) return;
            msg = UserPatients.deleteMyMedicalRedcordByPatientsId(Convert.ToInt32(departID));//执行删除并获取返回信息
            Response.Write("<script language=javascript>alert('" + msg + "');</script>");//弹出提示
            gdvAppointment.EditIndex = -1;
            gdvAppointmentBind();//重新绑定数据
            ddlDateDep_SelectedIndexChanged(sender, e);//重新绑定
        }



//个人信息-------------------------------------------------------------------------------------------------

        protected void ch_info_Click(object sender, EventArgs e)
        {
            Patients patient = (Patients)Session["patient"];
            patient.Nickname=c_nick.Text;
            patient.Patient_name=c_name.Text;
             patient.Telephone= c_tel.Text;
            patient.Age= int.Parse(c_age.Text);
            patient.Sex = c_sex.Text; ;
            patient.Id = int.Parse(c_id.Text) ;
            patient.State = int.Parse(c_sta.Text);
            PatientsDao dao = new PatientsDao();
            dao.update(patient);
            Session.Add("patient", patient);
            Response.Redirect("/user/index.aspx");
        }

        

        

        
    }
}